import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { clipboardApi, memoApi, Result } from "../backend/server";
import { store } from "./store";
import { addMemo } from "../../views/Functions/children/Memo/Memo";
import { toast } from "../../components/Toast/Toast";

const text: string = "";

export const clipboardSlice = createSlice({
  name: "clipboard",
  initialState: {
    text,
    // refresh: 0,
    loading: false,
  },
  reducers: {
    setLoading: (state, action: PayloadAction<boolean>) => {
      return {
        ...state,
        loading: action.payload,
      };
    },
    setClipboard: (state, action: PayloadAction<string>) => {
      return {
        ...state,
        text: action.payload,
      };
    },
  },
  extraReducers: (builders) => {
    builders.addCase(toDocx.fulfilled, (state, action) => {
      console.log(action);
      toast("convert success!");
    });
    builders.addCase(stashClipboard.fulfilled, (state, action) => {
      state.text = action.payload;
      toast("stashed!");
    });
    builders.addCase(fetchClipboard.fulfilled, (state, action) => {
      state.text = action.payload;
      // state.refresh = +new Date();
    });
  },
});

export const toDocx = createAsyncThunk<
  string,
  void,
  {
    rejectValue: string;
  }
>("clipboard/toDocx", async (params, action) => {
  const state = action.getState() as ReturnType<typeof store.getState>;
  try {
    return await clipboardApi.toDocx(state.clipboard.text);
  } catch (e) {
    return Promise.reject("failed to stash clipboard!");
  }
});

export const stashClipboard = createAsyncThunk<
  string,
  void,
  {
    rejectValue: string;
  }
>("clipboard/stashClipboard", async (params, action) => {
  const state = action.getState() as ReturnType<typeof store.getState>;
  try {
    // await clipboardApi.setClipboard(state.clipboard.text);
    await addMemo(state.clipboard.text);
  } catch (e) {
    return Promise.reject("failed to stash clipboard!");
  }

  return Promise.resolve("");
});

export const fetchClipboard = createAsyncThunk<
  string,
  void,
  { rejectValue: string }
>("clipboard/fetchClipboard", async (params, action) => {
  return (await clipboardApi.getClipboard()).content;
});

export const clipboardReducer = clipboardSlice.reducer;
export const { setClipboard, setLoading } = clipboardSlice.actions;
